package com.kaifamiao.jdbc.features;

import java.sql.*;

/**
 * 该类测试 可滚动结果集的 可更新特性(并发特性)
 * 通过向 可滚动结果集 中 插入新数据行 来影响数据库中的数据
 */
public class ResultSetUpdatable3 {

    public static void show( ResultSet rs ) throws SQLException {
        int id = rs.getInt( "id" );
        String name = rs.getString( "name" );
        System.out.printf("%d, %s\n", id, name );
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException{

        /*
        String driverClassName = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/kaifamiao?serverTimezone=Asia/Chongqing";
        String username = "kfm";
        String password = "kfm";
         */

        String driverClassName = "oracle.jdbc.OracleDriver";
        String url = "jdbc:oracle:thin:@localhost:1521:kaifamiao";
        String username = "kaifamiao";
        String password = "kaifamiao";

        Class.forName( driverClassName );
        Connection conn = DriverManager.getConnection( url, username, password );
        // 关闭事务自动提交
        conn.setAutoCommit( false );

        final String sql = "SELECT id, name FROM t_pandas ORDER BY id";
        final int type = ResultSet.TYPE_SCROLL_SENSITIVE; // 滚动特性: 可滚动、敏感
        final int concurrency = ResultSet.CONCUR_UPDATABLE; // 并发特性: 可更新

        PreparedStatement ps = conn.prepareStatement( sql, type, concurrency );

        ResultSet rs = ps.executeQuery();

        if( rs.absolute( 2 ) ) {
            show( rs );
        }

        System.out.println("- - - ".repeat( 5 ) );

        // 将游标移动到`插入行`
        rs.moveToInsertRow();
        rs.updateInt( "id" , 2233 );
        rs.updateString( "name" , "小然" );
        // 将`插入行`的数据插入到结果集中
        rs.insertRow();
        // 返回当前行(即原本在那一行就移动到那一行)
        rs.moveToCurrentRow();

        show( rs );

        System.out.println("- - - ".repeat( 5 ) );

        rs.beforeFirst();
        while( rs.next() ){
            show( rs );
        }

        Thread.sleep( 10000 );

        conn.commit();

        rs.close();

        // 启用事务自动提交
        conn.setAutoCommit( true );

        conn.close();

    }

}
